// 本文件由FirstUI授权予张铖（会员ID：2 1  68，身份证尾号：  1 21 99 6）专用，请尊重知识产权，勿私下传播，违者追究法律责任。
import http from '@/components/firstui/fui-request'
import {
	MainPages
} from '../config/router-config';
import {
	BASE_URL
} from '../_env';
import {
	useAuthStore
} from '../store/modules/auth';
import {
	useSyStemStore
} from '../store/modules/system';

//初始化请求配置项
http.create({
	host: BASE_URL,
	// host: 'http://192.168.20.8:8080',
	// header: { 
	// },

});
//请求拦截
http.interceptors.request.use(config => {
	const token = useAuthStore().token
	//请求之前可在请求头中加入token等信息   
	if (config.header) {
		config.header['Authorization'] = token || ''
	} else {
		config.header = {
			'Authorization': token || ''
		}
	}
	return config
})
//响应拦截
http.interceptors.response.use(response => {
	console.log(response);
	const {
		code,
		msg,
		version
	} = response
	if (code === 401) {
		uni.showModal({
			title: '提示',
			content: '账户未登录,跳转至登录页',
			showCancel: false,
			success() {
				uni.navigateTo({
					url: `${MainPages.LOGIN.router}`
				})
			}
		})
		return response
	} else if (code !== 200) {

		return Promise.reject(msg)
	} else {
		const token = useAuthStore().token
		if (token) {
			const s = useSyStemStore()
			if (s.version.dept != version.dept) {
				s.getDeptList()
			}
			if (s.version.dict != version.dict) {
				s.getDicList()
			}
			if (s.version.team != version.team) {
				s.getDeptTeamUserList()
				s.getTeamList()
				s.getTeamUserList()
			}
			// s.getTeamUserList()
			if (s.version.user != version.user) {
				s.getUserList()
			}
			s.setVersion(version)
		}


		return response
	}
})

export default http